
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class Rbook extends Books{

    Document document = null;
    Map<Integer,Books> map = new HashMap<>();

    public Rbook() {
    }

    public Rbook(String name, String type, double price) {
        super(name, type, price);
    }

    public void getDocument(){
        SAXReader saxReader = new SAXReader();
        try {
            document = saxReader.read(this.getClass().getResourceAsStream("/XML/books.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public void getInfo(){
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String name = element.elementText("name");
            String type = element.elementText("type");
            String p = element.elementText("price");
            double price = new Double(p);
            int id1 = new Integer(id);
            Books book = new Rbook(name,type,price);
            map.put(id1,book);
        }
    }

    public void show(){
        System.out.println("序号\t\t书名\t\t类型\t\t价格");
        Set<Integer> set = map.keySet();
        for (Integer integer : set) {
            System.out.print(integer+"\t");
            System.out.println(map.get(integer).getName()+"\t"+map.get(integer).getType()+"\t\t"+map.get(integer).getPrice());

        }
    }

    @Override
    public double Rent(int id) {
        double price = 0;
        boolean index = false;
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Element element : elements) {
            if(new Integer(id).toString().equals(element.attributeValue("id"))) {
                String name = element.elementText("name");
                String type = element.elementText("type");
                String p = element.elementText("price");
                price = new Double(p);
                System.out.println("选择的书名是："+name);
                System.out.println("类型为："+type);
                System.out.println("价格是："+price);
                element.getParent().remove(element);
                index = true;
                break;
            }
        }
        if(!index){
            System.out.println("没有这一本书");
        }
        return price;
    }
}
